/**
 * 在这里定义地址相关的路由处理函数，供 /router/wx_address.js 模块进行调用
 */
const {
	getMysqlPage,
	insertSqlPublic
} = require('./global')
// 处理 mysql 数据库里面的的表
const db = require('../db/index')


// 根据用户的openid来查询地址
exports.getList = async (req, res) => {
	let connection; // 声明 connection 变量
	try {
		// 等待从连接池中获取一个连接
		connection = await db.getConnection();
		// 接收表单数据
		const {
			openid,
			pageSize = 10,
			currentPage = 1
		} = req.body;
		// console.log(req.body)

		// 获取
		const addressSql = `SELECT * FROM cc_address WHERE openid = ? order by isdefault desc`
		let rows = await getMysqlPage(addressSql, [openid], { currentPage, pageSize })

		res.json({
			status: 200,
			message: '查询地址成功',
			data: rows
		});


	} catch (err) {
		console.error('Database connection error:', err);
		res.status(500).json({
			status: 500,
			message: '数据库连接错误'
		});
	} finally {
		// 释放连接
		if (connection) {
			connection.release();
		}
	}
};



//新增地址
exports.addAddress = async (req, res) => {
	let connection; // 声明 connection 变量
	try {
		// 等待从连接池中获取一个连接
		connection = await db.getConnection();
		const params = req.body;
		// console.log(params)
		const insertSql = await insertSqlPublic('cc_address', 'crab_card', params);
		const [rows] = await connection.query(insertSql);
		// console.log(rows)
		if (rows.affectedRows === 1) {
			res.json({ // 
				status: 200,
				message: '新增成功',
			});
		} else {
			res.status(400).json({ // 使用 400 表示 Bad Request
				status: 400,
				message: '新增失败'
			});
		}
	} catch (error) {
		console.error('Database connection error:', error);
		res.status(500).json({
			status: 500,
			message: '数据库连接错误'
		});
	} finally {
		// 释放连接
		if (connection) {
			connection.release();
		}
	}
};


//更新地址
exports.updateAddress = async (req, res) => {
	let connection; // 声明 connection 变量
	try {
		// 等待从连接池中获取一个连接
		connection = await db.getConnection();
		const params = req.body;
		const sql = `
		UPDATE 
			cc_address 
		SET
			name = ?, phone = ?, city = ?, detail = ?
		WHERE 
			id = ?;
		`;
		const [rows] = await connection.execute(sql, [params.name, params.phone, params.city, params.detail, params.id]);
		if(rows.affectedRows === 1){
			res.json({
				status: 200,
				message: '更新成功'
			});
		}else{
			res.status(400).json({
				status: 400,
				message: '更新失败'
			});
		}
	} catch (error) {
		console.error('Database connection error:', error);
		res.status(500).json({
			status: 500,
			message: '数据库连接错误'
		});
	} finally {
		// 释放连接
		if (connection) {
			connection.release();
		}
	}
};

//设置默认
exports.setDefault = async (req, res) => {
	let connection; // 声明 connection 变量
	try {
		// 等待从连接池中获取一个连接
		connection = await db.getConnection();
		const { id } = req.body;

		// 获取表中的记录总数
		const [countResult] = await connection.execute(`SELECT COUNT(*) AS count FROM cc_address;`);
		const totalRecords = countResult[0].count;

		// 开始事务
		await connection.beginTransaction();

		// 将所有记录的 isdefault 字段设置为 0
		const sql1 = `UPDATE cc_address SET isdefault = 0;`;
		const [rows1] = await connection.execute(sql1);

		// 检查是否所有记录都被更新
		if (rows1.affectedRows == totalRecords) {
			// 将匹配 id 的记录的 isdefault 字段设置为 1
			const sql2 = `UPDATE cc_address SET isdefault = 1 WHERE id = ?;`;
			const [rows2] = await connection.execute(sql2, [id]);

			// 检查是否至少有一条记录被更新
			if (rows2.affectedRows >= 1) {
				// 提交事务
				await connection.commit();
				res.json({
					status: 200,
					message: '设置成功',
				});
			} else {
				// 回滚事务
				await connection.rollback();
				res.status(400).json({
					status: 400,
					message: '设置失败'
				});
			}
		} else {
			// 回滚事务
			await connection.rollback();
			res.status(400).json({
				status: 400,
				message: '设置失败 - 无法更新所有记录'
			});
		}
	} catch (error) {
		console.error('Database connection error:', error);
		res.status(500).json({
			status: 500,
			message: '数据库连接错误'
		});
	} finally {
		// 释放连接
		if (connection) {
			connection.release();
		}
	}
};


// 移除
exports.remove = async (req, res) => {
	let connection; // 声明 connection 变量
	try {
		// 等待从连接池中获取一个连接
		connection = await db.getConnection();
		const { id } = req.body;
		const sql = `DELETE FROM cc_address WHERE id = ?`;
		const [rows] = await connection.execute(sql, [id]);
		if (rows.affectedRows === 1) {
			res.json({
				status: 200,
				message: '删除成功',
			});
		} else {
			res.status(400).json({
				status: 400,
				message: '删除失败'
			});
		}
	} catch (error) {
		console.error('Database connection error:', error);
		res.status(500).json({
			status: 500,
			message: '数据库连接错误'
		});
	} finally {
		// 释放连接
		if (connection) {
			connection.release();
		}
	}
};